package com.xinongbest.reader.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinongbest.reader.entity.Book;
import com.xinongbest.reader.entity.Category;
import com.xinongbest.reader.service.BookService;
import com.xinongbest.reader.service.CategoryService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class BookController {

    @Resource
    private CategoryService categoryService;

    @Resource
    private BookService bookService;

    @GetMapping("/")
    public ModelAndView showIndex() {
        ModelAndView modelAndView = new ModelAndView("/index");
        List<Category> list = categoryService.selectAll();
        modelAndView.addObject("categoryList", list);
        return modelAndView;
    }

    @GetMapping("/books")
    @ResponseBody
    public IPage<Book> selectBook(@RequestParam(value = "categoryId", defaultValue = "1") Long categoryId, String order, @RequestParam(value = "page", defaultValue = "1") Integer page) {
        return bookService.paging(categoryId, order, page, 10);
    }

    @GetMapping("/book/{id}")
    public ModelAndView showDetail(@PathVariable("id") Long bookId) {
        Book book = bookService.selectById(bookId);
        ModelAndView view = new ModelAndView("/detail");
        view.addObject("book", book);
        return view;
    }
}
